package com.google.utility;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

public final class JpaUtil {

	/**
	 * Create a new application-managed EntityManager.
	 * 
	 * @param entityManagerFactory
	 *            a EntityManagerFactory object.
	 * @return entity manager instance; or return null if entity manager factory
	 *         has been closed.
	 */
	static public EntityManager createEntityManager(
			EntityManagerFactory entityManagerFactory) {
		if (null != entityManagerFactory && entityManagerFactory.isOpen()) {
			return entityManagerFactory.createEntityManager();
		}
		return null;
	}

	/**
	 * Close entity manager.
	 * 
	 * @param entityManager
	 *            a EntityManager object to be closed.
	 */
	static public void closeEntityManager(EntityManager entityManager) {
		if (isOpenEntityManager(entityManager)) {
			entityManager.close();
		}
	}

	/**
	 * Begin a transaction in entity manager.
	 * 
	 * @param entityManager
	 *            a EntityManager object.
	 */
	static public void beginTransaction(EntityManager entityManager) {
		if (!isOpenEntityManager(entityManager)) {
			return;
		}

		final EntityTransaction transaction = entityManager.getTransaction();
		transaction.begin();
	}

	/**
	 * Commit a transaction in entity manager.
	 * 
	 * @param entityManager
	 *            a EntityManager object.
	 */
	static public void commitEntityManager(EntityManager entityManager) {
		if (!isOpenEntityManager(entityManager)) {
			return;
		}

		final EntityTransaction transaction = entityManager.getTransaction();
		if (isActiveTransaction(transaction)) {
			transaction.commit();
		}
	}

	/**
	 * Rollback a transaction in entity manager.
	 * 
	 * @param entityManager
	 *            a EntityManager object.
	 */
	static public void rollbackEntityManager(EntityManager entityManager) {
		if (!isOpenEntityManager(entityManager)) {
			return;
		}

		final EntityTransaction transaction = entityManager.getTransaction();
		if (isActiveTransaction(transaction)) {
			transaction.rollback();
		}
	}

	/**
	 * Indicates whether the entity manager is open. Returns true until the
	 * entity manager has been closed.
	 * 
	 * @param entityManager
	 *            a EntityManager object.
	 * @return boolean indicating whether the entity manager is open
	 */
	static public boolean isOpenEntityManager(EntityManager entityManager) {
		return null != entityManager && entityManager.isOpen();
	}

	/**
	 * Indicate whether a resource transaction is in progress.
	 * 
	 * @param transaction
	 *            a EntityTransaction object.
	 * @return boolean indicating whether the transaction is active
	 */
	static public boolean isActiveTransaction(EntityTransaction transaction) {
		return null != transaction && transaction.isActive();
	}

	/**
	 * Prevent constructor.
	 */
	private JpaUtil() {
	}

}
